package com.basin.micro.admin.module.department.pojo.vo;

import cn.hutool.core.util.ObjectUtil;
import com.basin.common.core.node.BasinTreeNode;
import com.basin.micro.admin.module.department.pojo.entity.DepartmentEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
public class DepartTreeVO extends BasinTreeNode<DepartmentEntity> {
    public DepartTreeVO(DepartmentEntity rootNode) {
        super(rootNode);
    }

    public static List<DepartTreeVO> build(List<DepartmentEntity> deptEntityList) {
        Map<String, DepartTreeVO> nodeMap = new HashMap<>();
        List<DepartTreeVO> rootNodes = new ArrayList<>();

        // 初始化节点映射
        for (DepartmentEntity depart : deptEntityList) {
            nodeMap.put(depart.getDeptCode(), new DepartTreeVO(depart));
        }

        // 构建树
        for (DepartmentEntity depart : deptEntityList) {
            // 获取节点集合对应的value值
            DepartTreeVO curNodeVal = nodeMap.get(depart.getDeptCode());
            // 如果没有父类节点 则代表是根节点
            if (ObjectUtil.isEmpty(depart.getParentCode())) {
                rootNodes.add(curNodeVal);
            } else {
                // 找到对应父节点 并加入其子节点
                DepartTreeVO parentNodeVal = nodeMap.get(depart.getParentCode());
                if (parentNodeVal != null) {
                    parentNodeVal.addChild(curNodeVal);
                }
            }
        }

        return rootNodes;
    }
}
